package com.moyun.syssecurity.sms.config;

import com.moyun.syssecurity.filter.JwtRequestFilter;
import com.moyun.syssecurity.handler.MyAuthenticationFailureHandler;
import com.moyun.syssecurity.handler.MyAuthenticationSuccessHandler;
import com.moyun.mapper.system.SysUserMapper;
import com.moyun.syssecurity.sms.filter.SmsCodeAuthenticationFilter;
import com.moyun.syssecurity.sms.provider.SmsCodeAuthenticationProvider;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;

/**
 * <h3>app-websocket.js</h3>
 * <p>手机验证码登录配置类</p>
 *
 * @author : ybx
 * @date : 2021-06-29 09:52:43
 **/
@Configuration
@RequiredArgsConstructor
public class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    private final SysUserMapper userMapper;
    private final StringRedisTemplate redisTemplate;
    // 在总的配置类中已经进行过了该配置
    private final MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    private final MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);

        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserMapper(userMapper);
        smsCodeAuthenticationProvider.setRedisTemplate(redisTemplate);


        http.authenticationProvider(smsCodeAuthenticationProvider)
                .addFilterBefore(smsCodeAuthenticationFilter, JwtRequestFilter.class);
    }
}